package com.cgy.utils.netx.helper;

import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @author CH
 */
public class NetsHelper<T> {

    /**
     * 流转对象
     * @param configPrefix
     * @param inputStream
     * @param classes
     * @param <T>
     * @return
     */
    public static <T>T initialConfigEntity(String configPrefix, InputStream inputStream, Class<T> classes) {
        List<String> strings = null;
        try {
            strings = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(null != strings) {
            String key, value;
            Map<String, Object> params = Maps.newHashMap();
            for (String string : strings) {
                String[] split = string.split("=");
                if(split.length > 1) {
                    key = split[0];
                    value = split[1];
                    if(StringUtils.isNotBlank(key)) {
                        params.put(key.replace(configPrefix, ""), value);
                    }
                }
            }

            try {
                return apply(classes, params, ClassLoader.getSystemClassLoader());
            } catch (IllegalAccessException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 渲染
     *
     * @param classes     类
     * @param params      参数
     *
     *                    <pre>
     * key:value
     *                    </pre>
     *
     * @param classLoader classloader
     * @param             <T> 实体对象
     * @return
     * @throws IllegalAccessException
     */
    public static <T> T apply(Class<T> classes, Map<String, Object> params, ClassLoader classLoader)
            throws IllegalAccessException {
        if (null == classLoader) {
            classLoader = Thread.currentThread().getContextClassLoader();
        }
        if (null == classes) {
            return null;
        }
        if (null == params || params.isEmpty()) {
            return null;
        }

        T t = null;
        try {
            t = classes.newInstance();
        } catch (Exception e) {
            return null;
        }
        Field declaredField = null;
        String key;
        String valueTrans = null;
        for (Map.Entry<String, Object> stringObjectEntry : params.entrySet()) {
            key = stringObjectEntry.getKey();
            if (key.indexOf("-") > -1) {
                StringBuilder stringBuilder = new StringBuilder();
                List<String> strings = Splitter.on("-").splitToList(key);
                for (int i = 0, size = strings.size(); i < size; i++) {
                    valueTrans = strings.get(i);
                    if (0 == i) {
                        stringBuilder.append(valueTrans);
                    } else {
                        if (null != valueTrans && valueTrans.length() > 0) {
                            stringBuilder.append(valueTrans.substring(0, 1).toUpperCase())
                                    .append(valueTrans.substring(1));
                        }
                    }
                }
                key = stringBuilder.toString();
            }
            try {
                declaredField = classes.getDeclaredField(key);
            } catch (NoSuchFieldException e) {
                continue;
            }

            if (null != declaredField) {
                declaredField.setAccessible(true);
                Class<?> type = declaredField.getType();
                String simpleName = type.getSimpleName();
                Object value = stringObjectEntry.getValue();
                if (null == value) {
                    continue;
                }
                String valueString = value.toString();
                if ("void".equals(simpleName)) {
                    continue;
                } else if ("boolean".equals(simpleName)) {
                    declaredField.set(t, BooleanUtils.toBoolean(valueString));
                } else if ("byte".equals(simpleName)) {
                    declaredField.set(t, NumberUtils.toByte(valueString));
                } else if ("char".equals(simpleName)) {
                    declaredField.set(t, (char) value);
                } else if ("double".equals(simpleName)) {
                    declaredField.set(t, NumberUtils.toDouble(valueString));
                } else if ("float".equals(simpleName)) {
                    declaredField.set(t, NumberUtils.toFloat(valueString));
                } else if ("int".equals(simpleName)) {
                    declaredField.set(t, NumberUtils.toInt(valueString));
                } else if ("long".equals(simpleName)) {
                    declaredField.set(t, NumberUtils.toLong(valueString));
                } else if ("short".equals(simpleName)) {
                    declaredField.set(t, NumberUtils.toShort(valueString));
                } else {
                    try {
                        declaredField.set(t, valueString);
                    } catch (Exception e) {
                    }
                }
            }
        }

        return t;
    }
}
